package com.example.demo.producer.controller;

import com.example.demo.common.domain.ChannelRead;
import com.example.demo.producer.domain.DeferredResultHolder;
import com.example.demo.producer.domain.TimeOutWork;
import com.example.demo.producer.service.ServerFingerService;
import com.example.demo.producer.task.RemoveCache;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.jms.Queue;

/**
 * @Auther Created by l.wang on 2019/4/3.
 */
@RestController
public class ActiveMqController {

    private JmsMessagingTemplate jmsMessagingTemplate;
    private JmsTemplate jmsTemplate;
    private Queue queue;
    private DeferredResultHolder resultHolder;
    private ServerFingerService serverFingerService;

    @Autowired
    public ActiveMqController(ServerFingerService serverFingerService, JmsMessagingTemplate jmsMessagingTemplate, JmsTemplate jmsTemplate, Queue queue, DeferredResultHolder resultHolder) {
        this.jmsMessagingTemplate = jmsMessagingTemplate;
        this.jmsTemplate = jmsTemplate;
        this.queue = queue;
        this.resultHolder = resultHolder;
        this.serverFingerService = serverFingerService;
    }


    @GetMapping("/test")
    public DeferredResult<ChannelRead> deferred(){
        String order = RandomStringUtils.randomNumeric(8);

        /** 此处将消息放入队列中 **/
        ChannelRead responseMsg = new ChannelRead();
        responseMsg.setCode(order).setMsg("发送信息").setFinger(serverFingerService.getServerFinger());
        jmsTemplate.convertAndSend(queue,responseMsg);

        DeferredResult<ChannelRead> deferredResult = new DeferredResult<>();
        System.out.println("生成order：" +  order);
        resultHolder.getMap().put(order,deferredResult);
        deferredResult.onTimeout(new TimeOutWork(deferredResult));//超时处理
        System.out.println("生产："+Thread.currentThread().getName());
        deferredResult.onCompletion(new RemoveCache(resultHolder,order));
        return deferredResult;

    }

}
